#!/usr/bin/perl

# Needs p5-Crypt-OpenSSL-RSA, p5-Crypt-OpenSSL-Bignum. Converts JSON-formatted
# private key on stdin (see /etc/letsencrypt/accounts/.../private_key.json)
# to a base64 key as used by acme-client(1).

use Crypt::OpenSSL::RSA;
use Crypt::OpenSSL::Bignum;
use JSON::PP;
use MIME::Base64;

my $json_content = <STDIN>;
$json_content =~ tr/-/+/;
$json_content =~ tr/_/\//;

my $json = decode_json($json_content);

my $n = Crypt::OpenSSL::Bignum->new_from_bin(decode_base64($json->{n}));
my $e = Crypt::OpenSSL::Bignum->new_from_bin(decode_base64($json->{e}));
my $d = Crypt::OpenSSL::Bignum->new_from_bin(decode_base64($json->{d}));
my $p = Crypt::OpenSSL::Bignum->new_from_bin(decode_base64($json->{p}));
my $q = Crypt::OpenSSL::Bignum->new_from_bin(decode_base64($json->{q}));

my $rsa = Crypt::OpenSSL::RSA->new_key_from_parameters($n, $e, $d, $p, $q);

print($rsa->get_private_key_string());
